package viper.sender.call;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Vector;

import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.format.AudioFormat;
import javax.media.protocol.DataSource;

import viper.call.common.LiveStream;
import viper.main.StateManager;

public class CallSender implements Runnable {
	//capture from mic, diversify, and send packets
	
	private VIPER_Sender transmitter;
	private LiveStream ls;
	
	public void run() {
		String ipArg = (String)StateManager.INSTANCE.getCalleeArray()[0];
		int destPort = StateManager.VIPER_PORT;
		
		DataSource source = null;

		InetAddress destIP = null;
		
		// Resolve IP Address
		try{
			destIP = InetAddress.getByName(ipArg);
		}catch(Exception uhe){
			System.err.println("Unknown Host Name.");
		}

		try {
			//Set type of audio format expected from capture device
			AudioFormat format = new AudioFormat(AudioFormat.LINEAR, //encoding type
					44100, //sampling frequency 
					16, //sample depth
					2); //channels

			// Get a list of connected capture devices and set the first available one
			// as the designated device
			Vector<?> devices = CaptureDeviceManager.getDeviceList(format);
			System.out.println("::Retrieving list of available capture devices...");
			CaptureDeviceInfo cdi = (CaptureDeviceInfo) devices.elementAt(0);
			//System.out.println("::Capture device set with the following properties: ");
			//System.out.println(cdi);

			//Create DataSource from capture device
			source = Manager.createDataSource(cdi.getLocator());
			System.out.println("::Capture Device connected!");

			//Construct VIPER object and assign capture device DataSource to it.
			VIPER_Sender transmitter = new VIPER_Sender(source);
			System.out.println("::DataSource Initialized!");

			//Begin encoding audio stream.
			transmitter.startEncoding();
			transmitter.getSource().start();
			System.out.println("::Audio Encoding Started...");

			//Extract data stream from DataSource object
			//Extractor also doubles as the transmitter that sends each individual packetized data.
			ls = transmitter.extract(destIP, destPort);
			System.out.println("::Transmitting to " + destIP + " on port " + destPort +"...");
			
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		System.out.println("CallSender started");
	}
	
	public void end()
	{
		ls.thread.interrupt();
		System.out.println("stop CallSender");
	}

}
